<?php
/* $Id: booklist.php 61 2011-02-22 16:54:49Z jim2212001@gmail.com $ */
require_once 'config.php';

$follower=hasPerm(PERM_FOLLOWER);
$tpl->assign('follower',$follower);
if(!$follower){
	infoMsg(MSG_BOOKLIST_READONLY);
}
/* get orderlist info */
$sql = 'SELECT * FROM `orderlist` WHERE `id`=\''.intval($_GET['id']).'\'';
$res = $db->query($sql,1);
if(($row = $res->fetch_assoc())===NULL)
	errMsg(MSG_BOOKLIST_ORDERLISTNOTFOUND,1);
if($row['startTime']>time() || $row['closedTime']<time())
	infoMsg(MSG_BOOKLIST_NOTACTIVE);
$tpl->assign('list',$row);
/* get booklist */
$sql = 'SELECT * FROM `booklist` WHERE `orderListId`=\''.intval($_GET['id']).'\'';
$res = $db->query($sql);
while($row = $res->fetch_assoc()){
	$books[$row['id']]=$row;
	$books[$row['id']]['value']=0;
}
/* get record */
if($follower){
	$res = $db->query('SELECT * FROM `followlist` WHERE `followerId`=\''.$_SESSION['id'].'\' AND `orderListId`=\''.intval($_GET['id']).'\' LIMIT 1',1);
	$hasRecord = $res->num_rows;
	$row = $res->fetch_assoc();
	$recordId = $row['id'];
	$record = json_decode($row['record']);
	if(is_array($record)){
		foreach($record as $v){
			$books[$v->id]['value'] = intval($v->value);
		}
	}
}
/* ajax add record */
if($_GET['action']=='addrecord'){
	if(!$follower)
		exit(json_encode(array('status'=>'fail','type'=>'perm')));
	$res = $_POST['record'];
	$res['status']='fail';
	foreach($res as $book){
	  	if(!is_array($book))continue;
		$dbRecord[] = $book;
		$field = 'book'.intval($book['id']);
		$res[$field] = intval($book['value']);
		$validate[]=array('type'=>'int','field'=>$field,'min'=>0);
	}
	ajaxValidate($res,$res,$validate);
	$dbRecord = json_encode($dbRecord);
	if($hasRecord){//update
	  	$sql = 'UPDATE `followlist` SET `record`=\''.$dbRecord.'\',`ip`=\''.$_SERVER['REMOTE_ADDR'].'\' WHERE `id`=\''.$recordId.'\' LIMIT 1';
	}else{
	  	$sql = 'INSERT INTO `followlist` (`followerId`,`orderListId`,`record`,`ip`) VALUES('.
		  "'".$_SESSION['id']."','".intval($_GET['id'])."','".$dbRecord."','".$_SERVER['REMOTE_ADDR']."')";
	}
	if($db->silentquery($sql)===false){
		$res['type']='mysql';
		exit(json_encode($res));
	}
	$res['status']='success';
	exit(json_encode($res));
}
/* encode $books */
if(is_array($books)){
	foreach($books as $v){
  		$json[] = json_encode($v);
	}
}
$tpl->assign('books',$json);
$tpl->assign('subtitle','檢視書單');
$tpl->display('booklist.htm');
?>
